import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService, NzModalService } from 'ng-zorro-antd'
import { STColumn, STData } from '@delon/abc'
import { ACLService } from '@delon/acl'
import { SettingsService } from '@delon/theme'

import { I18NService } from '@core'
import { UserService } from '../user.service'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { User, IUserQueryParams } from '@shared/interfaces/user'
import { ISearchSchema } from '@shared/interfaces/search'
import { ESearchType, EUserType, EUserStatus } from '@shared/enums'
import { StatusTextMap, UserTypeTextMap } from '@shared/interfaces/common'
import { AAMSFilterInit } from '@shared/interfaces/aams'

@Component({
  selector: 'app-user-common-user-table',
  templateUrl: './list.component.html',
  styleUrls: ['../../../shared/styles/table.less'],
})
export class UserListComponent extends ListBaseClass<User, IUserQueryParams> implements OnInit, AAMSFilterInit {
  updateStatus = [
    { label: this.trans('GENERAL.STATUS.NORMAL'), value: EUserStatus.Normal },
    { label: this.trans('GENERAL.STATUS.FREEZE'), value: EUserStatus.Freeze },
  ]
  StatusTextMap = StatusTextMap
  UserTypeTextMap = UserTypeTextMap
  data: User[] = []

  userStatus: string
  userType: string

  @ViewChild('tplStatus') tplStatus: TemplateRef<void>
  @ViewChild('tplAcquirer') tplAcquirer: TemplateRef<void>
  @ViewChild('tplGroup') tplGroup: TemplateRef<void>
  @ViewChild('tplMerchant') tplMerchant: TemplateRef<void>
  @ViewChild('tplStore') tplStore: TemplateRef<void>
  @ViewChild('tplUserType') tplUserType: TemplateRef<void>

  /* 搜索数据 */
  searchSchema: ISearchSchema[] = []

  /* 自定义搜索 */
  customSchema: ISearchSchema[] = [
    {
      label: 'USER.USER_TYPE',
      labelI18n: 'USER.USER_TYPE',
      index: 'userType',
      type: ESearchType.selection,
    },
  ]

  /* 单元格名称 */
  columns: STColumn[] = []

  constructor(
    public msg: NzMessageService,
    public modal: NzModalService,
    public i18n: I18NService,
    public userService: UserService,
    public settings: SettingsService,
    public router: Router,
    public route: ActivatedRoute,
    private aclService: ACLService,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit() {
    this.initColumns()
    this.parseParams().subscribe(() => {
      this.queryTableDataWithParams()
    })
    this.searchSchema = this.createSearchSchema()
    this.initialAAMSFilter()
    this.setupUserTypeSelectionPermit()
  }

  initialAAMSFilter() {
    this.initAcquirer()
    this.initAgent()
    this.initMerchant()
    this.initStore()
  }

  public queryTableDataWithParams() {
    const { page } = this.params
    this.loading = true
    this.userService.getList(this.params).subscribe(respData => {
      const { data, total } = respData
      this.data = data.map((d, index: number) => {
        d.no = (page - 1) * 20 + index + 1
        return d
      })
      this.total = total
      this.loading = false
    })
  }

  goDetail(user: User) {
    const { username } = user
    this.router.navigate([`../${username}`], { relativeTo: this.route })
  }

  getUserLevelID(user: User): string {
    switch (user.userType) {
      case EUserType.Institution: {
        return user.insCode
      }
      case EUserType.Agent: {
        return user.agentCode
      }
      case EUserType.Merchant: {
        return user.intMerCode
      }
      case EUserType.Store: {
        return user.intStoreCode
      }
      default:
        return ''
    }
  }

  getUserType(userType: string): string {
    try {
      return this.trans(UserTypeTextMap[userType])
    } catch (e) {
      return this.trans('GENERAL.INFO.NONE')
    }
  }

  getUserStatus(status: string): string {
    try {
      return this.trans(StatusTextMap[status])
    } catch (e) {
      return this.trans('GENERAL.INFO.NONE')
    }
  }

  freezeDialog(user: User) {
    const { username } = user
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.USER_FREEZE_CONFIRM', { username }),
      nzOnOk: () => this.freezeUser(username),
    })
  }

  freezeUser(username: string): void {
    this.userService.freeze(username).subscribe(
      values => {
        this.st.reload()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.FREEZE_SUCCESS'))
      },
      err => {
        console.error(err)
        this.msg.error(this.trans('GENERAL.NOTIFICATION.FREEZE_FAIL'))
      },
    )
  }

  deleteUserDialog(user, _modal, comp): void {
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.USER_DELETE_CONFIRM', { username: user.username }),
      nzOnOk: () => this.deleteUser(user, comp),
    })
  }

  deleteUser(user: User, comp): void {
    this.userService.delete(user.username).subscribe(
      values => {
        this.st.reload()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.DELETE_SUCCESS'))
      },
      err => {
        console.error(err)
        this.msg.success(this.trans('GENERAL.NOTIFICATION.DELETE_FAIL'))
      },
    )
  }

  // 解冻用户
  unfreezeUserDialog(user: User): void {
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.USER_UNFREEZE_CONFIRM', { username: user.username }),
      nzOnOk: () => this.unfreezeUser(user.username),
    })
  }

  unfreezeUser(username: string): void {
    this.userService.unfreeze(username).subscribe(
      values => {
        this.st.reload()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_SUCCESS'))
      },
      err => {
        console.error(err)
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_FAIL'))
      },
    )
  }

  handleAction(): void {
    console.log('action 按钮被按啦')
  }

  private initColumns(): void {
    const canLock = this.aclService.canAbility('api.put.camel.user.one.freeze')
    const canUnlock = this.aclService.canAbility('api.put.camel.user.one.unfreeze')
    const canDelete = this.aclService.canAbility('api.delete.camel.user.one')
    this.columns = [
      {
        type: 'link',
        title: 'USER.USERNAME',
        i18n: 'USER.USERNAME',
        index: 'username',
        fixed: 'left',
        width: '80px',
        className: 'text-center',
        click: this.goDetail.bind(this),
      },
      {
        title: 'USER.NAME',
        i18n: 'USER.NAME',
        index: 'nickName',
        fixed: 'left',
        width: '80px',
        className: 'text-center',
      },
      {
        title: 'GENERAL.INFO.EMAIL',
        i18n: 'GENERAL.INFO.EMAIL',
        index: 'email',
        fixed: 'left',
        width: '80px',
        className: 'text-center',
      },
      {
        title: '用户类型',
        i18n: 'USER.USER_TYPE',
        index: 'userType',
        width: '100px',
        className: 'text-center',
        render: 'userType',
      },
      {
        title: '关联层级编号',
        i18n: 'GENERAL.INFO.BIZ_LEVEL_CODE',
        index: 'level',
        width: '100px',
        className: 'text-center',
        render: 'userTypeParentID',
      },
      {
        title: 'GENERAL.INFO.STATUS',
        i18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        width: '100px',
        className: 'text-center',
        render: 'status',
      },
      {
        title: 'GENERAL.INFO.OPERATION',
        i18n: 'GENERAL.INFO.OPERATION',
        fixed: 'right',
        width: '100px',
        className: 'text-center',
        iif: () => canLock || canUnlock || canDelete,
        buttons: [
          {
            icon: {
              iconfont: 'icon-delete-circle',
              type: 'iconfont',
            },
            click: this.deleteUserDialog.bind(this),
            iif: () => canDelete,
          },
          {
            icon: {
              iconfont: 'icon-lock-twotone',
              type: 'iconfont',
            },
            click: this.freezeDialog.bind(this),
            iif: record => canLock && (record.status === 'normal' || record.status === ''), // status 有可能为空值
          },
          {
            icon: {
              iconfont: 'icon-unlock-circle',
              type: 'iconfont',
            },
            click: this.unfreezeUserDialog.bind(this),
            iif: record => canUnlock && record.status === 'freeze',
          },
        ],
      },
    ]
  }

  private createSearchSchema(): ISearchSchema[] {
    return [
      {
        label: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        labelI18n: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        index: 'insCode',
        component: this.tplAcquirer,
        customFunc: () => this.selectedAcquirer && this.selectedAcquirer.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.AGENT',
        labelI18n: 'GENERAL.BIZ_LEVEL.AGENT',
        index: 'agentCode',
        component: this.tplGroup,
        customFunc: () => this.selectedGroup && this.selectedGroup.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.MERCHANT',
        labelI18n: 'GENERAL.BIZ_LEVEL.MERCHANT',
        index: 'intMerCode',
        component: this.tplMerchant,
        customFunc: () => this.selectedMerchant && this.selectedMerchant.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.STORE',
        labelI18n: 'GENERAL.BIZ_LEVEL.STORE',
        index: 'intStoreCode',
        component: this.tplStore,
        customFunc: () => this.selectedStore && this.selectedStore.code,
      },
      {
        label: 'USER.USERNAME',
        labelI18n: 'USER.USERNAME',
        index: 'username',
        type: ESearchType.input,
      },
      {
        label: 'USER.NAME',
        labelI18n: 'USER.NAME',
        index: 'nickName',
        type: ESearchType.input,
      },
      {
        label: 'USER.USER_TYPE',
        labelI18n: 'USER.USER_TYPE',
        index: 'userType',
        component: this.tplUserType,
        customFunc: () => this.userType,
      },
      {
        label: 'GENERAL.INFO.EMAIL',
        labelI18n: 'GENERAL.INFO.EMAIL',
        index: 'email',
        type: ESearchType.input,
      },
      {
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        component: this.tplStatus,
        customFunc: () => this.userStatus,
      },
    ]
  }
}
